package sound;

import java.net.URL;
import java.util.HashMap;
import java.applet.Applet;
import java.applet.AudioClip;

/**
 * A resource handler for sound files, controls the loading, playing and 
 * destruction of sound files
 * 
 * @author Neil Cowzer, Scott Nelson
 */
public class SoundCache{
//	 The single instance of this class
	private static SoundCache cache = new SoundCache();

	/**
	 * Get the single instance of this class
	 * @return cache
	 */
	public  /*@ pure @*/ static SoundCache getCache() {
		return cache;
	}
	
	/** The cached sprite map */
	private HashMap<String, AudioClip> sounds = new HashMap<String, AudioClip>();

	/**
	 * Retrieve a AudioClip or if neccessary add another AudioClip to the cache.
	 * 
	 * @param name the string reference of the sprite
	 * @return An instance of a sprite
	 */
	/*@ requires name != null
	 *  assignable cache
	 *  ensures true
	@*/
	public AudioClip getSound(String name) {
		// if sprite has been loaded, return the sprite
		if (sounds.get(name) != null){
			return (AudioClip)sounds.get(name);
		}
		
		// Otherwise load the sound
		AudioClip sound = null;
		URL url=null;
		try {
			url = getClass().getClassLoader().getResource(name);
			sound = Applet.newAudioClip(url);
			System.out.println("Loaded!");
		} catch (Exception e) {
			System.out.println("Unable to load: " + name);
			System.out.println(e.getClass().getName()+" "+e.getMessage());
			System.exit(0);
			return null;
		}
		
		// Store the Sound in the HashMap
		sounds.put(name, sound);
		
		// return the image
		return (AudioClip)sounds.get(name);
	}
	
	/** Play the sound file */
	//@ requires name != null
	public void play(String name){
		getSound(name).play();
	}
	
	/** Conitnuously loop a sound file */
	//@ requires name != null
	public void loopSound(String name){
		getSound(name).loop();
	}
	
	/** Stop playing sounds */
	//@ requires name != null
	public void stop(String name){
		getSound(name).stop();
	}
	
	/** Clear SoundCache.*/
	public void clear(){
		sounds.clear();
	}

}
